package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-08-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        queryWrapper.in(Elder::getStatus, 1, 4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("该老人已入住");
        }
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
         elder = insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(), bed);
         String contractNo = "HT"+CodeGenerator.generateContractNumber();
         insertContract(contractNo, elder, checkInApplyDto);
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);
        insertCheckInConfig(checkIn.getId(), checkInApplyDto.getCheckInConfigDto());


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckInElderVo checkInElderVo = selectElderVo(checkIn);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        String remark = checkIn.getRemark();
        checkInDetailVo.setElderFamilyVoList(JSON.parseArray(remark, ElderFamilyVo.class));
        CheckInConfigVo checkInConfigVo = selectCheckInConfigVo(checkIn);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        LambdaQueryWrapper<Contract> queryWrapperContract = new LambdaQueryWrapper<>();
        queryWrapperContract.eq(Contract::getElderId, checkInElderVo.getId());
        Contract contract = contractMapper.selectOne(queryWrapperContract);
        checkInDetailVo.setContract( contract);
        return checkInDetailVo;
    }

    private CheckInConfigVo selectCheckInConfigVo(CheckIn checkIn) {
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties( checkInConfig, checkInConfigVo);
        return checkInConfigVo;
    }

    private CheckInElderVo selectElderVo(CheckIn checkIn) {
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        Date currentDate = DateUtils.parseDate(DateUtils.getTime());
        Date birthDate = DateUtils.parseDate(elder.getBirthday());

        long ageInMillis = currentDate.getTime() - birthDate.getTime();
        long age = ageInMillis / (1000L * 60 * 60 * 24 * 365);
        checkInElderVo.setAge(age);
        return checkInElderVo;
    }
    private void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto){
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status =startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        if(endDate.isBefore(LocalDateTime.now())){
            status = 2;
        }
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, elder.getIdCardNo()).in(Elder::getStatus, 1, 4);
        Elder oldElder = elderMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNotEmpty(oldElder)){
            elder.setId(oldElder.getId());
            elderMapper.updateById(elder);
        }
        else {
            elderMapper.insert(elder);
        }
        return elder;
    }
}
